Discuss the differences between deep copy and shallow copy in Java objects.
192
17-Jul-2024
Ravi Vishwakarma
17-Jul-2024Shallow Copy
A shallow copy of an object is a new object whose fields are the same as the original object. However, if the field is a reference to an object, the reference is copied, but the referred object is not. Consequently, both the original object and the shallow copy will reference the same nested objects.
Characteristics of Shallow Copy:
int
,char
, etc.) are copied directly.Object
the class performs a shallow copy.Example:
Deep Copy
A deep copy of an object involves creating a new object and then recursively copying all objects referenced by the original object. Consequently, changes to the objects referenced by the original object do not affect the deep copy.
Characteristics of Deep Copy:
Example:
Summary
Read more
What is the difference between JDK, JRE, and JVM?
Bitwise AND, OR, XOR, and left/right shift operations.